package xworker.netty.handlers.codec;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.xmeta.ActionContext;
import org.xmeta.Thing;

import java.util.List;

public class ThingMessageToMessageDecoder extends MessageToMessageDecoder<Object> {
    Thing thing;
    ActionContext actionContext;

    public ThingMessageToMessageDecoder(Thing thing, ActionContext actionContext){
        this.thing = thing;
        this.actionContext = actionContext;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
        thing.doAction("decode", actionContext, "ctx", ctx, "msg", msg, "out", out);
    }

    public static ThingMessageToMessageDecoder create(ActionContext actionContext){
        Thing self = actionContext.getObject("self");

        ThingMessageToMessageDecoder decoder = new ThingMessageToMessageDecoder(self, actionContext);
        actionContext.g().put(self.getMetadata().getName(), decoder);

        return decoder;
    }

}
